package com.eshore.norm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormConfig;
import com.eshore.norm.pojo.dto.NormHost;
import com.eshore.norm.mapper.NormHostMapper;
import com.eshore.norm.pojo.po.NormHypervisorHostPO;
import com.eshore.norm.pojo.po.NormResourceProvidersPO;
import com.eshore.norm.pojo.vo.SyncCmdbHostVO;
import com.eshore.norm.service.INormHostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 宿主机列表 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Slf4j
@Service
public class NormHostServiceImpl extends ServiceImpl<NormHostMapper, NormHost> implements INormHostService {
    @Override
    public void insertOrUpdateBatch(List<NormHost> entitys) {
        getBaseMapper().insertOrUpdateBatch(entitys);
    }

    @Override
    public void dataImport(NormResourceProvidersPO po) {
        if (po != null) {
            List<NormResourceProvidersPO.ResourceProvidersDTO> resourceProviders = po.getResourceProviders();
            if (CollectionUtils.isEmpty(resourceProviders)) {
                return;
            }
            List<String> newUuid = resourceProviders.stream().map(NormResourceProvidersPO.ResourceProvidersDTO::getUuid).collect(Collectors.toList());
            List<String> oldUuids = cleanOldData(Const.CONFIG_ID, newUuid);
            //TODO 将po转化成NormHost入库
            List<NormHost> normHosts = toNormHost(Const.CONFIG_ID, resourceProviders);
            if (!CollectionUtils.isEmpty(normHosts)) {
                getBaseMapper().insertOrUpdateBatch(normHosts);

                //同步cmdb
                syncHostToCmdb(normHosts, oldUuids, Const.RESOURCE_ID, Const.TENANT_CODE);
            }
        }
    }

    /**
     * 同步cmdbHost信息
     */
    public void syncHostToCmdb(List<NormHost> normHosts, List<String> oldUuids, Long resourceId, Long tenantCode) {
        List<SyncCmdbHostVO> hostItemVOList = normHosts.stream().map(item -> {
            SyncCmdbHostVO hostItemVO = new SyncCmdbHostVO();
            String hostname = item.getName();

            Long usedMemory = 0L;
            Long usedCpu = 0L;
            Long usedStorage = 0L;
            Long memorySize = 0L;
            Long storageSize = 0L;
            //宿主机监控信息
            try {
                if (true) {
                    String poJson = "{\"message\":\"请求成功\",\"content\":[{\"cpu\":\"336\",\"cpu_ratio\":\"4.9\",\"memory\":\"843.0\",\"memory_ratio\":\"3.3\",\"storage\":\"19\",\"storage_ratio\":\"22.0\",\"vm_count\":\"1\",\"running_count\":\"0\",\"hostname\":\"ZH-IT03-H12-U12-CZZWYXC-zwwwCom-TS02F-05\",\"uuid\":\"34B3A5C349553D4A8BEE4192FE0B5310\"}],\"status\":200,\"total\":1,\"timestamp\":\"2024-01-25T10:13:14.906\"}";
                    NormHypervisorHostPO po = JSON.parseObject(poJson, NormHypervisorHostPO.class);
                    log.info("========》po:" + po);
                    if (po != null && !CollectionUtils.isEmpty(po.getContent())) {
                        NormHypervisorHostPO.ContentDTO contentDTO = po.getContent().get(0);
                        if (contentDTO != null) {
                            usedMemory = Math.round(Double.parseDouble(contentDTO.getMemory()) * Double.parseDouble(contentDTO.getMemoryRatio()));
                            usedCpu = Math.round(Double.parseDouble(contentDTO.getCpu()) * Double.parseDouble(contentDTO.getCpuRatio()));
                            usedStorage = Math.round(Double.parseDouble(contentDTO.getStorage()) * Double.parseDouble(contentDTO.getStorageRatio()));
                            memorySize = Math.round(Double.parseDouble(contentDTO.getMemory()));
                            storageSize = Math.round(Double.parseDouble(contentDTO.getStorage()));

                        }
                    }
                }
            }catch (Exception e){
                log.info(e.getMessage());
            }finally {
                log.info("========》usedMemory:"+usedMemory+",usedCpu:"+usedCpu+",usedStorage:"+usedStorage+",memorySize:"+memorySize+",storageSize:"+storageSize);
            }
            hostItemVO.setId(item.getId())
                    .setHostId(item.getUuid())
                    .setAccountId(item.getConfigId())
//                    .setResourceType(CmdbResTypeEnums.NORM)
//                    .setCloudType(CloudTypeEnum.PRIVATE)
                    .setHostName(hostname)
                    .setResourceId(resourceId)
                    .setMemorySize(memorySize)
                    .setUsedMemory(usedMemory)
                    .setUsedCpu(usedCpu)
                    .setStorageSize(storageSize)
                    .setUsedStorage(usedStorage)
                    .setTenantCode(tenantCode);
            return hostItemVO;
        }).collect(Collectors.toList());
     //   log.info("hostItemVOList:"+hostItemVOList);
//        SyncMessageContent<SyncCmdbHostVO> messageContent = new SyncMessageContent<>();
//        messageContent.setCloudType(SyncMessageContent.CLOUD_TYPE_NORM_CLOUD);
//        messageContent.setResourceType(SyncMessageContent.RESOURCE_TYPE_SYNC_HOST);
//        messageContent.setAddOrUpdateDatas(hostItemVOList);
//        messageContent.setRemoveStrIds(oldUuids);
//        rabbitService.defaultDirectSend(SyncMessageContent.QUEUE_NAME, JSONObject.toJSONString(messageContent));
    }

    /**
     * 删除现已不存在的数据，保持同步一致
     *
     * @param configId
     * @param newUuid
     * @author v-chenjl62
     * @date 2024/1/9
     */
    private List<String> cleanOldData(Long configId, List<String> newUuid) {
        List<String> oldUuids = lambdaQuery().eq(NormHost::getConfigId, configId).list().stream().map(NormHost::getUuid).collect(Collectors.toList());
        //筛选出差异的uuid即为删除的uu
        oldUuids.removeAll(newUuid);
        if (!CollectionUtils.isEmpty(oldUuids)) {
            getBaseMapper().delete(new QueryWrapper<NormHost>().in("uuid", oldUuids));
            return oldUuids;
        }
        return null;
    }

    /**
     * 转换为 NormHost 实体对象
     *
     * @param list
     * @author v-chenjl62
     * @date 2024/1/9
     */
    public List<NormHost> toNormHost(Long configId, List<NormResourceProvidersPO.ResourceProvidersDTO> list) {
        return Optional.ofNullable(list).get().stream().map(item -> {
            NormHost entity = new NormHost();
            BeanUtils.copyProperties(item, entity, "links");
            entity.setId(IdWorker.getId());
            entity.setConfigId(configId);
//            entity.setCreateDate(LocalDateTime.now());
//            entity.setUpdateDate(LocalDateTime.now());
            entity.setLinks(JSON.toJSONString(item.getLinks(), SerializerFeature.WriteMapNullValue));
            return entity;
        }).collect(Collectors.toList());


    }

}
